Kotlin
Enum Classes
Swift
|
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
|
enum Direction {
case north
case south
case west
case east
}
enum Direction {
case north, south, west, east
}
|
Initialization
|
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
|
enum Color : Int {
case red = 0xFF0000
case gree = 0x00FF00
case blue = 0x0000FF
}
enum Color : String {
case red = "0xFF0000"
case gree = "0x00FF00"
case blue = "0x0000FF"
}
let color = Color.red
let rgb = color.rawValue
|
Anonymous Classes
|
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
}
|
enum ProtocolState {
case waiting, talking
func signal() -> ProtocolState {
switch self {
case .waiting:
return .talking
case .talking:
return .waiting
}
}
}
let state = ProtocolState.waiting.signal()
|
Implementing Interfaces in Enum Classes
|
enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
PLUS {
override fun apply(t: Int, u: Int): Int = t + u
},
TIMES {
override fun apply(t: Int, u: Int): Int = t * u
};
override fun applyAsInt(t: Int, u: Int) = apply(t, u)
}
|
protocol IntBinaryOperator {
func apply(_ t: Int, _ u: Int) -> Int
}
enum IntArithmetics: IntBinaryOperator {
case plus, times
func apply(_ t: Int, _ u: Int) -> Int {
switch self {
case .plus:
return t + u
case .times:
return t * u
}
}
}
IntArithmetics.plus.apply(13, 31)
IntArithmetics.times.apply(13, 31)
|
Working with Enum Constants
|
EnumClass.valueOf(value: String): EnumClass
EnumClass.values(): Array<EnumClass>
|
enum Direction : String, CaseIterable {
case north, south, west, east
}
Direction(rawValue: "north") //Direction.north
Direction.allCases
Direction.north.rawValue
|
enum class RGB { RED, GREEN, BLUE }
inline fun <reified T : Enum<T>> printAllValues() {
print(enumValues<T>().joinToString { it.name })
}
printAllValues<RGB>() // prints RED, GREEN, BLUE
|
|
val name: String
val ordinal: Int
|
|